<template>
  <!-- 编辑生产计划 -->
  <div class="plan-modal">
    <a-modal :width="1200" :render-to-body="false" v-model:visible="showDetail" :ok-loading="submitLoading" okText="保存" :mask-closable="false" @cancel="closedDialog" :on-before-ok="saveData">
      <div class="edit-product-plan-wrap">
        <div class="header">
          <a-space :size="40">
            <p class="highlight">{{ detailInfo.billNo }}</p>
            <p>计划创建时间：{{ $setTime(detailInfo.gmtCreate) }}</p>
            <p>接单日期：{{ $setTime(detailInfo.gmtAccept, 'YYYY-MM-DD') }}</p>
            <p>期望交货日期：{{ $setTime(detailInfo.gmtExpectDelivery, 'YYYY-MM-DD') }}</p>
          </a-space>
        </div>
        <div class="edit-product-plan-con">
          <div class="left">
            <ImgPopover :src="detailInfo.productImg">
              <template #con>
                <a-image width="180" height="180" fit="contain" :src="detailInfo.productImg" />
              </template>
            </ImgPopover>
            <div class="product-info">
              <p>品名：{{ detailInfo.productName }}</p>
              <p>SKU：{{ detailInfo.sku }}</p>
              <p>SPU：{{ detailInfo.spu }}</p>
              <p>类目：{{ detailInfo.cateName }}</p>
              <p style="margin-bottom: 20px">规格：{{ getProductSpecs(detailInfo) }}</p>
            </div>
          </div>
          <div class="right">
            <a-form :model="detailInfo" ref="formRef" :label-col-props="{ span: 4 }" :wrapper-col-props="{ span: 20 }" :rules="rules">
              <a-form-item label="客户">
                <p>{{ detailInfo.purchaseCompanyName }}</p>
              </a-form-item>
              <a-form-item label="采购数量">
                <p>{{ detailInfo.purchaseAmt }}</p>
              </a-form-item>
              <a-form-item label="现货库存">
                <p>{{ detailInfo.amtAvailable }}</p>
              </a-form-item>
              <a-form-item field="productionAmt" label="需生产数量">
                <div class="flex-c" style="width: 100%">
                  <a-input-number :precision="0" :min="1" v-model="detailInfo.productionAmt" placeholder="" style="width: 160px; margin-right: 10px" hide-button />
                  <span>生产数量必须大于等于1</span>
                </div>
              </a-form-item>
              <a-form-item label="类型">
                <p>{{ productTypeMap[detailInfo.productType] || detailInfo.productType }}</p>
              </a-form-item>
              <a-form-item label="材质">
                <p>{{ getMaterial(detailInfo) }}</p>
              </a-form-item>
              <a-form-item label="生产入库仓">
                <a-select v-model="detailInfo.warehouseInfo" value-key="warehouseCode" allow-search allow-clear placeholder="" style="width: 300px">
                  <a-option v-for="(item, i) in useBaseData.warehouseList" :key="i" :value="item" :label="item.warehouseName" />
                </a-select>
              </a-form-item>
              <a-form-item label="生产工序">
                <a-select size="medium" v-model="detailInfo.productionProcedureId" allow-search allow-clear placeholder="" style="width: 300px">
                  <a-option v-for="(el, i) in productionProcedure" :key="i" :value="el.id" :label="el.templateName" />
                </a-select>
                <icon-plus-circle class="highlight cursor add-procedure" @click="showProductionProcedure = true" />
              </a-form-item>
              <a-form-item field="remark" label="备注">
                <a-textarea placeholder="生产注意事项" size="mini" style="height: 60px" v-model="detailInfo.remark" />
              </a-form-item>
              <a-form-item field="purchaseSpecs" label="生产参数">
                <a-textarea placeholder="" size="mini" style="height: 100px" v-model="detailInfo.purchaseSpecs" />
              </a-form-item>
            </a-form>
            <div class="parets-w">
              <setProductParets ref="productParetsRef" :list="detailInfo.partsList" />
            </div>
          </div>
        </div>
      </div>
      <SetProductionProcedure v-if="showProductionProcedure" :list="productionProcedure" :isShow="showProductionProcedure" @closed="showProductionProcedure = false" @success="getProductionProcedure" />
    </a-modal>
  </div>
</template>
<script lang="ts" setup>
  import { ref, onMounted } from 'vue'
  import { Message } from '@arco-design/web-vue'
  import { updateProductionPlan, findProductionProcedurePage, getProductionPlanInfo } from '@/api/purchaseApplication'
  import SetProductParets from './setProductParets.vue'
  import SetProductionProcedure from './setProductionProcedure.vue'
  import { cloneDeep } from 'lodash-es'
  import { parseJson } from '@/utils'
  import useBaseDataStore from '@/store/modules/base-data'

  onMounted(() => {
    useBaseData.getWareHouseList()
    getProductionProcedure()
    setDefaultData()
  })

  const emit = defineEmits(['closed', 'success'])
  const props = defineProps({
    isShow: {
      type: Boolean,
      default: false,
    },
    currentId: {
      type: String,
    },
  })
  const useBaseData = useBaseDataStore()
  const showDetail = ref(props.isShow)
  const submitLoading = ref(false)
  const detailInfo = ref<any>({})
  const productionProcedure = ref<Array<any>>([])
  const productParetsRef = ref()
  const showProductionProcedure = ref(false)
  const formRef = ref()
  const productTypeMap = {
    1: '普货',
    2: '打样',
    3: '定制',
  }
  const rules = ref({
    productionAmt: [{ required: true, message: '生产数量必须大于等于1' }],
    purchaseSpecs: [{ required: true, message: '请输入生产参数' }],
  })

  // 显示sku规格
  function getProductSpecs(item: any) {
    let productSpecs = item.productSpecs ? parseJson(item.productSpecs, []) : []
    return productSpecs.map((el: any) => el.valueCn)?.join('*') || '--'
  }
  // 获取材质
  function getMaterial(row: any) {
    let propArr = row.purchaseSpecsArr || []
    return propArr.find((el: any) => el.name == '材质')?.purchaseValue
  }
  // 获取生产工序模板列表
  async function getProductionProcedure() {
    const res: any = await findProductionProcedurePage({
      pageSize: 100,
      pageNum: 1,
    })
    productionProcedure.value = res?.data?.records || []
  }
  async function setDefaultData() {
    const res: any = await getProductionPlanInfo({ id: props.currentId })
    detailInfo.value = res?.data || {}
    if (detailInfo.value.warehouseCode) {
      detailInfo.value.warehouseInfo = {
        warehouseCode: detailInfo.value.warehouseCode,
        warehouseName: detailInfo.value.warehouseName,
      }
    }
  }

  async function saveData() {
    let valid = await formRef.value.validate((valid: any) => {
      return valid
    })
    if (valid) return false
    let _params: any = cloneDeep(detailInfo.value)
    _params.partsList = productParetsRef.value.getPartsList()
    console.log(_params.partsList)
    let flag = false
    let nameFlag = false
    if (_params.partsList?.length) {
      _params.partsList.forEach((el: any) => {
        if (!el.partsName) {
          nameFlag = true
        }
        if (!el.partsAmt && !el.partsWeight) {
          flag = true
        }
      })
      if (nameFlag) {
        Message.error('配件名称不能为空！')
        return false
      }
      if (flag) {
        Message.error('配件数量和重量必须填写一个！')
        return false
      }
    }
    if (_params.warehouseInfo?.id) {
      _params.warehouseCode = _params.warehouseInfo.warehouseCode
      _params.warehouseName = _params.warehouseInfo.warehouseName
    }
    delete _params.warehouseName
    const res: any = await updateProductionPlan(_params)
    if (!res) return false
    Message.success('保存成功')
    emit('success')
    emit('closed')
  }
  // 关闭
  function closedDialog() {
    showDetail.value = false
    emit('closed')
  }
</script>
<style lang="less"></style>
<style lang="less" scoped>
  .plan-modal {
    :deep(.arco-modal-header) {
      display: none;
    }
  }
  .edit-product-plan-wrap {
    height: calc(84vh - 100px);
    overflow: auto;
    padding-bottom: 20px;
    .header {
      padding: 10px 20px;
      border: 1px solid #ddd;
      margin-bottom: 5px;
    }
    .edit-product-plan-con {
      display: flex;
      .left {
        width: 200px;
        margin-right: 10px;
        border: 1px solid #ddd;
        padding: 0 10px;
        flex-shrink: 0;
      }
      .right {
        flex: 1;
        .arco-form {
          border: 1px solid #ddd;
          border-bottom: 0;
          :deep(.arco-form-item) {
            margin-bottom: 0;
            border-bottom: 1px solid #ddd;
            .arco-form-item-label-col {
              padding: 10px;
            }
            .arco-form-item-wrapper-col {
              padding: 10px 10px;
              border-left: 1px solid #ddd;
            }
          }
        }
        .add-procedure {
          font-size: 18px;
          margin-left: 10px;
        }
      }
    }
  }
</style>
